package com.aef.controller;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;


import org.jdom2.JDOMException;

import com.aef.service.RecycleService;
import com.aef.service.WeixinUserService;
import com.aef.utils.IsNumberUtils;
import com.aef.utils.ResultModel;
import com.aef.utils.ResultStatus;
import com.alibaba.fastjson.JSONObject;
import com.http.test.TestCase;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.RedPackApi;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.jfinal.weixin.sdk.api.UserApi;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.weixin.sdk.utils.Base64Utils;

public class RecycleController extends WeixinMsgController  {
	private static String appid = PropKit.get("appId");
	private static String secret = PropKit.get("appSecret");
	private static String redirect_uri=PropKit.get("domain")+"recycle/getList";
	private static String redirect_uri1=PropKit.get("domain")+"recycle/getdataList";
	private static String TemplateMsgid="4LGpjKVmlBcYfMPeKihPVYZOrnQ64sQo0IbYbmIcP9E";
	private static String admin_TemplateMsgid="4LGpjKVmlBcYfMPeKihPVYZOrnQ64sQo0IbYbmIcP9E";
	// 新增OpenId
	private static final String insertOpenIdurl="http://118.178.18.0:8082/alfa-mobile-ws/rest/OpenId/insertOpenId";
	//private static final String insertOpenIdurl="http://120.27.192.10/alfa-mobile-ws/rest/OpenId/insertOpenId";
	RecycleService recycleService=new RecycleService();
	WeixinUserService weixinUserService=new WeixinUserService();
	public void index() {
		redirect(SnsAccessTokenApi.getAuthorizeURL(appid,redirect_uri,false));
	}

	public void getList() {
		ApiConfigKit apiConfigKit=new ApiConfigKit();
		apiConfigKit.setThreadLocalApiConfig(getApiConfig());
		AccessTokenApi accesstokenapi=new AccessTokenApi();
		String code=getPara("code");
		System.out.println("code:"+code);
		SnsAccessToken snsAccessToken=SnsAccessTokenApi.getSnsAccessToken(appid, secret, code);
		String openid=snsAccessToken.getOpenid();
		/*System.out.println(openid);*/
		/* TextToUser("<a href='www.baidu.com'>sssss</a>", openid, accesstokenapi.getAccessTokenStr());*/
		setAttr("openid", openid);
		renderJsp("/weixinuser/appointment.jsp");
	}
	public void index1() {
		redirect(SnsAccessTokenApi.getAuthorizeURL(appid,redirect_uri1,false));
	}

	public void getdataList() {
		ApiConfigKit apiConfigKit=new ApiConfigKit();
		apiConfigKit.setThreadLocalApiConfig(getApiConfig());
		AccessTokenApi accesstokenapi=new AccessTokenApi();
		String code=getPara("code");
		System.out.println("code:"+code);
		SnsAccessToken snsAccessToken=SnsAccessTokenApi.getSnsAccessToken(appid, secret, code);
		String openid=snsAccessToken.getOpenid();
		/*System.out.println(openid);*/
		/* TextToUser("<a href='www.baidu.com'>sssss</a>", openid, accesstokenapi.getAccessTokenStr());*/
		setAttr("openid", openid);
		renderJsp("/weixinuser/data.jsp");
	}
	public void JudgeOpenidbund(){
	/*	String openid=getPara("openid");
		renderJson(recycleService.JudgeOpenidbund(openid));*/
	}
	public void TextToUser(){
		headers();
		String jsonString = HttpKit.readData(getRequest());
		JSONObject jsonObject=JSONObject.parseObject(jsonString);
		ApiConfigKit apiConfigKit=new ApiConfigKit();
		apiConfigKit.setThreadLocalApiConfig(getApiConfig());
		AccessTokenApi accesstokenapi=new AccessTokenApi();
		String openid=jsonObject.get("openid").toString();
		if(openid.equals("")){
			renderJson(ResultModel.error(ResultStatus.USER_OPENIDNULL));
		}else{
			TextToUser("您的订单已提交,请保持电话畅通。", openid, accesstokenapi.getAccessTokenStr());
			renderJson(ResultModel.ok("发送成功"));
		
		}
		
	}
	public void addopenidinfo(){
		headers();
		String jsonString = HttpKit.readData(getRequest());
		JSONObject jsonObject=JSONObject.parseObject(jsonString);
		ApiConfigKit apiConfigKit=new ApiConfigKit();
		apiConfigKit.setThreadLocalApiConfig(getApiConfig());
		AccessTokenApi accesstokenapi=new AccessTokenApi();
		String openid=jsonObject.get("openid").toString();
		JSONObject userjson=JSONObject.parseObject(UserApi.getUserInfo(openid).getJson());
		Map<String, String> bodyParam=new HashMap<String,String>();
		
		if(userjson.getString("headimgurl")=="") {
			bodyParam.put("state", "-1");
			renderJson(ResultModel.error(ResultStatus.USERNAME_OR_PASSWORD_ERROR));
		}else {
			bodyParam.put("openid", userjson.getString("openid"));
			bodyParam.put("headimgurl", userjson.getString("headimgurl"));
			bodyParam.put("nickname", userjson.getString("nickname"));
			bodyParam.put("state", "0");
			String json = JSONObject.toJSONString(bodyParam); 
			TestCase.post(json,insertOpenIdurl);
			renderJson(ResultModel.ok("添加成功"));
		}
		
	}
	public void TextToSleaman(){
		headers();
		String jsonString = HttpKit.readData(getRequest());
		JSONObject jsonObject=JSONObject.parseObject(jsonString);
		ApiConfigKit apiConfigKit=new ApiConfigKit();
		apiConfigKit.setThreadLocalApiConfig(getApiConfig());
		AccessTokenApi accesstokenapi=new AccessTokenApi();
		String openid=jsonObject.get("openid").toString();
		String time=jsonObject.get("time").toString();
		String orderid=jsonObject.get("orderid").toString();
		String iphon=jsonObject.get("iphon").toString();
		String orderno=jsonObject.get("orderno").toString();
		if(openid.equals("")||time.equals("")||orderid.equals("")||iphon.equals("")){
			renderJson(ResultModel.error(ResultStatus.USER_OPENIDNULL));
		}else{
			ApiResult apiResult = TemplateMsgApi.send(TemplateData.New().setTemplate_id(TemplateMsgid)
			.setTouser(openid)
			.setUrl("http://tugo.cn/weixin_aef/weixinuser/newhtml/user_Comment.jsp?phone="+iphon+"&orderId="+orderid+"")
			.add("first", "尊敬的客户,您好！\n您的订单完成,感谢您的使用。", "#999")
			.add("keyword1", orderno+"\n", "#999").add("keyword2", "您的订单完成,感谢您的使用。", "#999").add("remark", time, "#999").build());
			String jsonResult = apiResult.getJson();
			System.out.println(jsonResult);
			renderJson(jsonResult);
		
		}
		
	}
	public void TextToAdmin(){
		headers();
		String jsonString = HttpKit.readData(getRequest());
		JSONObject jsonObject=JSONObject.parseObject(jsonString);
		ApiConfigKit apiConfigKit=new ApiConfigKit();
		apiConfigKit.setThreadLocalApiConfig(getApiConfig());
		AccessTokenApi accesstokenapi=new AccessTokenApi();
		String openid=jsonObject.get("openid").toString();
		String time=jsonObject.get("time").toString();
		String name=jsonObject.get("name").toString();
		System.out.println(jsonObject);
		if(openid.equals("")||time.equals("")||name.equals("")){
			renderJson(ResultModel.error(ResultStatus.USER_OPENIDNULL));
		}else{
			ApiResult apiResult = TemplateMsgApi.send(TemplateData.New().setTemplate_id(admin_TemplateMsgid)
			.setTouser(openid)
			.add("first", "您好,用户"+name+"在"+time+"提交了一笔订单,请及时分配！\n", "#999")
			.add("keyword1", time+"\n", "#999").add("keyword2", "请及时分配！", "#999").add("remark", time, "#999").build());
			String jsonResult = apiResult.getJson();
			System.out.println(jsonResult);
			renderJson(jsonResult);
		
		}
		
	}
	/**
	 * 红包发送接口
	 * @throws JDOMException
	 * @throws IOException
	 */
	public void ToRedPack() throws JDOMException, IOException{
		headers();
		String jsonString = HttpKit.readData(getRequest());
		JSONObject jsonObject=JSONObject.parseObject(jsonString);
		String openid=Base64Utils.decode(jsonObject.get("openid").toString());
		String key=Base64Utils.decode(jsonObject.get("key").toString());
		String num=Base64Utils.decode(jsonObject.get("num").toString());
		String paykey=Base64Utils.decode(jsonObject.get("paykey").toString());
		if("".equals(openid)){
			renderJson(ResultModel.error(ResultStatus.USER_PAYOPENIDRROR));
		}else if("".equals(key)) {
			renderJson(ResultModel.error(ResultStatus.USER_KEYRROR));
		}else if("".equals(num)) {
			renderJson(ResultModel.error(ResultStatus.USER_MONEYRROR));
		}else if("".equals(paykey)) {
			renderJson(ResultModel.error(ResultStatus.USER_PAYKEYRROR));
		}else {
			if(IsNumberUtils.isNumeric(num)) {
				Double cny = Double.parseDouble(num);//6.2041    这个是转为double类型  
				DecimalFormat df = new DecimalFormat("0.00");   
				String CNY = df.format(cny); //6.20   这个是字符串，但已经是我要的两位小数了  
				Double numnow = Double.parseDouble(CNY); //6.20  
				if(numnow>0&&numnow<200) {
					 Map <String,String> map = new HashMap <String,String>();  
				        map.put("nonce_str",IsNumberUtils.createNonceStr());  
				        map.put("mch_billno",IsNumberUtils.createBillNo(key)); //值等于商户号+ yyyymmdd + 10数字要唯一  
				        map.put("mch_id",key); //商户号  
				        map.put("wxappid",appid); //微信公众号appid  
				        map.put("send_name","途狗收油");  
				        map.put("re_openid",openid); //对应公众号  
				        map.put("total_amount",  
				                String.valueOf((int)(Float.parseFloat(num)* 100)));  
				        map.put("total_num","1");  
				        map.put("wishing","感谢语测试");  
				        map.put("client_ip","127.0.0.1"); //服务器地址这个需要跟微信公众平台红包管理里面那个IP地址一样  
				        map.put("act_name","活动测试语");  
				        map.put("remark","说明测试语");  
				        String sign = PaymentKit.createSign(map,paykey);  
				        map.put("sign",sign);  
				        String apiResult =RedPackApi.sendRedPack(map, "D:\\cert\\apiclient_cert.p12", key);
				        JSONObject json=IsNumberUtils.xml2JSON(apiResult.getBytes());
						JSONObject json1=(JSONObject) json.get("xml");
						String err_code= json1.get("err_code").toString().replaceAll("\\[\"", "").replaceAll("\"\\]", "").replaceAll("\\]", "").replaceAll("\\[", "");
						String return_msg=json1.get("return_msg").toString().replaceAll("\\[\"", "").replaceAll("\"\\]", "").replaceAll("\\]", "").replaceAll("\\[", "");
						System.out.println(err_code);
						if(err_code.equals("SUCCESS")) {
							 renderJson(ResultModel.ok());
						}else {
							 renderJson(ResultModel.errorcontent(ResultStatus.SIGN_ERROR,return_msg));
						}
				       
				}else {
					renderJson(ResultModel.error(ResultStatus.USER_NUMERROR));
				}
			}else {
				renderJson(ResultModel.error(ResultStatus.USER_NUMERROR));
			}
		}
	}

	public  void headers(){
		getResponse().addHeader("Access-Control-Allow-Origin", "*");
		getResponse().addHeader("Access-Control-Allow-Credentials", "true");
		getResponse().addHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
		getResponse().addHeader("Access-Control-Max-Age", "3600");
		getResponse().addHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers");
	}
	

}
